package com.cb2.algorithm.leetcode;

import java.util.ArrayList;
import java.util.List;

/**
 * <a href='https://leetcode.cn/problems/letter-combinations-of-a-phone-number/'>电话号码的字母组合(Letter Combinations of a Phone Number)</a>
 * <p>给定一个仅包含数字 2-9 的字符串，返回所有它能表示的字母组合。答案可以按 任意顺序 返回。</p>
 * <p>给出数字到字母的映射如下（与电话按键相同）。注意 1 不对应任何字母。
 * <ul>
 *      <li>2: a b c</li>
 *      <li>3: d e f</li>
 *      <li>4: g h i</li>
 *      <li>5: j k l</li>
 *      <li>6: m n o</li>
 *      <li>7: p q r s</li>
 *      <li>8: t u v</li>
 *      <li>9: w x y z</li>
 * </ul>
 * </p>
 *
 * <p>
 * <b>示例：</b>
 * <pre>
 * 示例 1：
 *      输入：digits = "23"
 *      输出：["ad","ae","af","bd","be","bf","cd","ce","cf"]
 *
 * 示例 2：
 *      输入：digits = ""
 *      输出：[]
 *
 * 示例 3：
 *      输入：digits = "2"
 *      输出：["a","b","c"]
 *     </pre>
 * </p>
 *
 * <p>
 * <b>提示：</b>
 * <ul>
 *      <li>0 <= digits.length <= 4</li>
 *      <li>digits[i] 是范围 ["2", "9"] 的一个数字。</li>
 * </ul>
 * </p>
 *
 * @author c2b
 * @since 2025/2/12 15:30
 */
public class LC0017LetterCombinationsOfPhoneNumber_M {
    static class Solution {
        public List<String> letterCombinations(String digits) {
            List<String> resList = new ArrayList<>();
            if (digits.length() == 0) {
                return resList;
            }
            backtracking(digits, 0, new StringBuilder(), resList,
                    new String[]{"", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"});
            return resList;
        }

        private void backtracking(String digits, int currIdx, StringBuilder path, List<String> resList, String[] num2lettersMap) {
            if (digits.length() == currIdx) {
                resList.add(path.toString());
                return;
            }
            String letters = num2lettersMap[digits.charAt(currIdx) - '1'];
            for (int idx = 0; idx < letters.length(); idx++) {
                path.append(letters.charAt(idx));
                backtracking(digits, currIdx + 1, path, resList, num2lettersMap);
                path.deleteCharAt(path.length() - 1);
            }
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        Printer.printListString(solution.letterCombinations("23"));
        Printer.printListString(solution.letterCombinations(""));
        Printer.printListString(solution.letterCombinations("2"));
    }

}
